/*
 * @Descripttion: 
 * @version: 
 * @Author: ChenXiang
 * @Date: 2021-04-28 21:42:05
 * @LastEditors: ChenXiang
 * @LastEditTime: 2021-04-29 10:55:54
 */
const chalk = require('chalk')
const inquirer = require('inquirer')
const fs = require('fs')
const memFs = require('mem-fs');
const memFsEditor = require('mem-fs-editor');
const path = require('path');
const getGitUser = require('./git-user')

class Creator {
    constructor() {
        // 创建内存store
        const store = memFs.create();
        this.fs = memFsEditor.create(store);

        this.options = {
            name: '',
            description: '',
        };

        // 当前根目录
        this.rootPath = path.resolve(__dirname, '../');
        // 模版目录
        this.tplDirPath = path.join(this.rootPath, 'template');
    }

    // 初始化；
    init() {
        console.log(chalk.green('初始化'));
        console.log();
        this.ask().then((answers) => {
            this.options = Object.assign({}, this.options, answers);
            this.write();
        });
    }

    // 和命令行交互；
    ask() {
        const prompt = [];
        prompt.push({
            type: 'input',
            name: 'name',
            message: '请输入项目名称',
            validate(input) {
                if (!input) {
                    return '请输入项目名称!';
                }

                if (fs.existsSync(input)) {
                    return '项目名已重复!'
                }

                return true;
            }
        });
        prompt.push({
            type: 'input',
            name: 'description',
            message: '请输入项目描述',
        });

        prompt.push({
            type: 'input',
            name: 'author',
            message: '请输入开发者',
            default: getGitUser()
        });


        // 返回promise
        return inquirer.prompt(prompt);
    }

    // 拷贝&写数据；
    write() {
        console.log(chalk.green('开始构建'));
        const tplBuilder = require('./template.js');
        tplBuilder(this, this.options, () => {
            console.log(chalk.green('构建完成'));
            console.log();
            console.log(chalk.grey(`启动项目:  cd ${this.options.name} && npm install`));
        });
    }

    getTplPath(file) {
        return path.join(this.tplDirPath, file);
    }
    //拷贝文件并注入数据
    copyTpl(file, to, data = {}) {
        const tplPath = this.getTplPath(file);
        this.fs.copyTpl(tplPath, to, data);
    }
    //直接拷贝文件
    copy(file, to) {
        const tplPath = this.getTplPath(file);
        this.fs.copy(tplPath, to);
    }
    delete(file) {
        const tplPath = this.getTplPath(file);
        this.fs.delete(tplPath);
    }

}

module.exports = Creator;
